package top.haijunit.navi.auth.utils;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.RandomUtil;
import lombok.SneakyThrows;
import lombok.experimental.UtilityClass;
import top.haijunit.framework.core.exception.ExceptionServer;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.geom.AffineTransform;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.*;

/**
 * 【说明类功能】
 *
 * @author zhanghaijun
 * @since 2024-09-23
 */
@UtilityClass
public class AvatarUtils {
    //图片宽度
    private static final int WIDTH = 100;
    //图片高度
    private static final int HEIGHT = 100;

    @SneakyThrows
    public File generateImageToFile(String name) {
        String uuid = IdUtil.fastSimpleUUID();
        String fileName = "./store/avatar/" + uuid + ".png";
        File file = new File(fileName);
        FileUtil.mkParentDirs(file);
        ImageIO.write(generateImg(name), "png", file);
        return file;
    }

    public String generateImageFileToBase64(String name) {
        try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            ImgUtil.write(generateImg(name), "png", outputStream);
            byte[] imageBytes = outputStream.toByteArray();
            return "data:image/jpg;base64," + Base64.encode(imageBytes);
        } catch (Exception e) {
            return null;
        }
    }


    @SneakyThrows
    public BufferedImage generateImg(String name) {
        String nameWritten = name.length() <= 2 ? name : CharSequenceUtil.subWithLength(name, name.length() - 2, 2);

        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = image.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        g2.setBackground(getRandomColor());
        g2.clearRect(0, 0, WIDTH, HEIGHT);
        g2.setPaint(Color.WHITE);

        try (InputStream inputStream = ResourceUtil.getStream("static/fonts/syht.otf"); BufferedInputStream fontStream = new BufferedInputStream(inputStream)) {
            Font font = Font.createFont(Font.TRUETYPE_FONT, fontStream);
            switch (nameWritten.length()) {
                case 1:
                    font = font.deriveFont(Font.BOLD, 50);
                    g2.setFont(font);
                    g2.drawString(nameWritten, (WIDTH - getWordWidth(font, nameWritten)) / 2, 70);
                    break;
                case 2:
                default:
                    font = font.deriveFont(Font.BOLD, 30);
                    g2.setFont(font);
                    g2.drawString(nameWritten, (WIDTH - getWordWidth(font, nameWritten)) / 2, 60);
            }
        } catch (FontFormatException | IOException e) {
            throw new ExceptionServer("Error loading font", e);
        }
        BufferedImage rounded = makeRoundedCorner(image, 20);
        g2.dispose(); // 释放图形上下文资源
        return rounded;
    }

    /**
     * 得到该字体字符串的长度
     */
    public int getWordWidth(Font font, String content) {
        FontRenderContext frc = new FontRenderContext(new AffineTransform(), true, true);
        Rectangle rec = font.getStringBounds(content, frc).getBounds();
        return (int) rec.getWidth();
    }

    /**
     * 生成随机颜色
     */
    private Color getRandomColor() {
        String[] predefinedColors = new String[]{"2,168,250", "51,153,204", "51,102,255", "102,0,204", "102,102,51", "99,0,99", "204,51,204", "255,153,102"};
        int length = predefinedColors.length;
        String colorString = predefinedColors[RandomUtil.randomInt(length)];
        String[] colorComponents = colorString.split(",");
        return new Color(Integer.parseInt(colorComponents[0]), Integer.parseInt(colorComponents[1]), Integer.parseInt(colorComponents[2]));
    }

    /**
     * 图片做圆角处理
     */
    public BufferedImage makeRoundedCorner(BufferedImage image, int cornerRadius) {
        int w = image.getWidth();
        int h = image.getHeight();
        BufferedImage output = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2 = output.createGraphics();
        g2.setComposite(AlphaComposite.Src);
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
        g2.setColor(Color.WHITE);
        g2.fill(new RoundRectangle2D.Float(0, 0, w, h, cornerRadius, cornerRadius));
        g2.setComposite(AlphaComposite.SrcAtop);
        g2.drawImage(image, 0, 0, null);
        g2.dispose();
        return output;
    }
}
